// 引入pinia
import { defineStore } from "pinia";
import { ref, reactive, watch } from "vue";
import router from "../router";
function initState() {
  return {
    isCollapse: false,
    tags: [
      {
        path: "/home",
        name: "home",
        label: "首页",
        icon: "house",
      },
    ],
    currentMenu: null,
    token: "",
    menuList: [],
    routerList: [],
  };
}

export const useAllDataStore = defineStore("useAllDataStore", () => {
  const state = ref(initState());
  watch(
    state,
    (newVal) => {
      if (!newVal.token) return;
    //   console.log(newVal);
      localStorage.setItem("store", JSON.stringify(newVal));
    },
    {
      deep: true,
    }
  );
  function selectMenu(menu) {
    // 如果菜单名称为 'home'，则将当前菜单设置为 null
    if (menu.name === "home") {
      state.value.currentMenu = null;
    } else {
      state.value.currentMenu = menu;
      const result = state.value.tags.findIndex(
        (item) => item.name === menu.name
      );
      result === -1 ? state.value.tags.push(menu) : "";
    }
  }
  function updateTags(tag) {
    let result = state.value.tags.findIndex((item) => item.name === tag.name);
    state.value.tags.splice(result, 1);
  }
  function updataMenuList(val) {
    state.value.menuList = val;
  }
  function addMenu(router,type) {

    if(type === 'refresh'){
      if(JSON.parse(localStorage.getItem('store'))){
        state.value = JSON.parse(localStorage.getItem('store'));
        state.value.routerList = [];
      }else{
        return
      }
    }


    const menu = state.value.menuList;
    
    const module = import.meta.glob("../views/**/*.vue");
    // console.log(module);
    const routeArr = [];
    menu.forEach((item) => {
      if (item.children) {
        item.children.forEach((val) => {
          let url = `../views/${val.url}.vue`;
          val.component = module[url];
          routeArr.push(...item.children);
        });
      } else {
        let url = `../views/${item.url}.vue`;
        item.component = module[url];
        routeArr.push(item);
      }
    });
    state.value.routerList = [];
    let routers = router.getRoutes();
    routers.forEach((item) => {
      if (item.name == "main" || item.name == "login"||item.name == "404") {
        return;
      } else {
        router.removeRoute(item.name);
      }
    });
    routeArr.forEach((item) => {
      state.value.routerList.push(router.addRoute("main", item));
    });
  }
  function clear(){
    state.value.routerList.forEach((item) => {
        // router.removeRoute(item.name);
        if(item) router.removeRoute(item.name);
      });
    state.value = initState();
    // 删除本地缓存
    localStorage.removeItem('store');
    // 跳转到登录页面
    router.push('/login');
  }
  return { state, selectMenu, updateTags, updataMenuList, addMenu,clear};
});
